package com.enjoy.tree;

import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;

public class BinaryTreeTest {
    public class TreeNode {
        private char data;

        private TreeNode left;

        private TreeNode right;

        public TreeNode(char data, TreeNode left, TreeNode right) {
            this.data = data;
            this.left = left;
            this.right = right;
        }

        public char getData() {
            return data;
        }

        public TreeNode getLeft() {
            return left;
        }

        public TreeNode getRight() {
            return right;
        }
    }

    // 前序遍历 根左右
    public void pre(TreeNode root) {
        System.out.println(root.getData());

        if (root.getLeft() != null) {
            pre(root.getLeft());
        }

        if (root.getRight() != null) {
            pre(root.getRight());
        }
    }

    // 中序遍历 左根右
    public void in(TreeNode root) {

        if (root.getLeft() != null) {
            in(root.getLeft());
        }

        System.out.println(root.getData());

        if (root.getRight() != null) {
            in(root.getRight());
        }
    }

    // 后序遍历 左右根
    public void post(TreeNode root) {
        if (root.getLeft() != null) {
            post(root.getLeft());
        }

        if (root.getRight() != null) {
            post(root.getRight());
        }
        System.out.println(root.getData());
    }

    public void sequence(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();
            System.out.println(treeNode.getData());
            if (treeNode.getLeft() != null) {
                queue.offer(treeNode.getLeft());
            }
            if (treeNode.getRight() != null) {
                queue.offer(treeNode.getRight());
            }
        }
    }



    @Test
    public void test1() {
        TreeNode a = init();
        pre(a);
    }

    @Test
    public void test2() {
        TreeNode a = init();
        in(a);
    }

    @Test
    public void test3() {
        TreeNode a = init();
        post(a);
    }

    @Test
    public void test4() {
        TreeNode a = init();
        sequence(a);
    }

    TreeNode init() {
        TreeNode e = new TreeNode('E', null, null);
        TreeNode d = new TreeNode('D', null, null);
        TreeNode f = new TreeNode('F', null, null);
        TreeNode c = new TreeNode('C', f, null);
        TreeNode b = new TreeNode('B', d, e);
        return new TreeNode('A', b, c);
    }
}


